#pragma once

#include <iostream>
#include <unistd.h>
#include <queue>
#include <pthread.h>

const int defaultcap = 5;

template <typename T>
class BlockQueue
{
private:
    bool isFull() { return _q.size() >= _capacity; }
    bool isEmpty() { return _q.empty(); }

public:
    BlockQueue(int cap = defaultcap)
        : _capacity(cap),
          _consumernumber(0),
          _productornumber(0)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_full_con,nullptr);
        pthread_cond_init(&_empty_con,nullptr);
    }

    void EnterQueue(const T& cond)
    {
        pthread_mutex_lock(&_mutex);
        //这里使用while是因为如果pthread_cond_wait失败后
        //会导致伪唤醒,实际条件并没有满足
        while(isFull())
        {
            // 应该让生产者线程进行等待
            // 重点1：pthread_cond_wait调用成功，挂起当前线程之前，要先自动释放锁！！
            // 重点2：当线程被唤醒的时候，默认就在临界区内唤醒！要从pthread_cond_wait
            // 成功返回，需要当前线程，重新申请_mutex锁！！！
            // 重点3：如果我被唤醒，但是申请锁失败了？？我就会在锁上阻塞等待！！！
            _productornumber++;
            std::cout << "生产者进入休眠了" << _productornumber <<std::endl;
            pthread_cond_wait(&_full_con,&_mutex);
            _productornumber--;
        }

        _q.push(cond);

        if(_consumernumber > 0)
        {
            pthread_cond_signal(&_empty_con);
            std::cout << "唤醒消费者" << std::endl;
        }

        // pthread_cond_signal(&_empty_con);
        pthread_mutex_unlock(&_mutex);
    }

    T pop()
    {
        pthread_mutex_lock(&_mutex);

        while(isEmpty())
        {
            _consumernumber++;
            std::cout << "消费者进入休眠了" << std::endl;
            pthread_cond_wait(&_empty_con,&_mutex);
            _consumernumber--;
        }

        T data = _q.front();
        _q.pop();

        if(_productornumber > 0)
        {
            pthread_cond_signal(&_full_con);
            std::cout << "唤醒消费者" << std::endl;
        }
        
        pthread_mutex_unlock(&_mutex);
        return data;
    }

    ~BlockQueue()
    {
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_full_con);
        pthread_cond_destroy(&_empty_con);
    }

private:
    std::queue<T> _q;
    int _capacity;
    pthread_mutex_t _mutex;
    pthread_cond_t _full_con;
    pthread_cond_t _empty_con;

    int _consumernumber;
    int _productornumber;
};